package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.cache.RedisCached;
import top.infopub.dto.mkt.ProjectSellDto;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.StatusMarketingExpenses;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.ProSellDomain;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.ProSellService;
import top.infopub.mgr.mkt.service.ProjectSellDtoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.mkt.vo.ProSellVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.ProSell;
import top.infopub.model.mkt.ProSellCost;
import top.infopub.model.mkt.ProjectInfo;
import top.infopub.model.mkt.SetupPro;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 营销策划管理
 *
 * @author wangw
 * @version 2020年1月9日
 * @see ProSellController
 * @since
 */
@Controller
@RequestMapping("/proSell")
public class ProSellController extends GenericFlowController {

    @Autowired
    private ProSellService proSellService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private ProjectSellDtoService projectSellDtoService;
    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private RedisCached  redisCached;
    //营销策划详情页面
    @RequestMapping("/queryDetail")
    @ResponseBody
    public ProjectSellDto queryDetail(String code) throws ParseException {
        ProjectSellDto dto = projectSellDtoService.queryDetail(code);
        return dto;
    }

    //查询人员表的人员名称 在职 工号 职务
    @RequestMapping("/queryPersonnel")
    @ResponseBody
    public List<StaffInfo> queryDetail() throws Exception {
//        List<StaffInfo> staffInfoList = projectSellDtoService.queryPersonnel();
//        return staffInfoList;
        /*redis*/
        Object cached = redisCached.getCached("staffInfoList");
        if (cached!=null)
        {
            String json = cached.toString();
            List<StaffInfo> list = JSON.parseArray(json,StaffInfo.class);
            return  list;
        }else {
            List<StaffInfo> staffInfoList = projectSellDtoService.queryPersonnel();
            String json = JSONArray.toJSONString(staffInfoList);
            redisCached.addCachedExpireSec("staffInfoList",json,24*60*60);
            return staffInfoList;
        }
    }

    //查询营销策划费用类型
    @RequestMapping("/costTypes")
    @ResponseBody
    public List<Map<String, String>> costTypes() {
        List<Map<String, String>> maps = StatusMarketingExpenses.asList();
        return maps;
    }


    //营销策划详情的业主单位下拉框
    @RequestMapping("/queryCoopInfo")
    @ResponseBody
    public List<CoopInfo> selectCoopInfoIdAndCoopNameAll() {
        List<CoopInfo> coopInfoArrayList = new ArrayList<CoopInfo>();
        coopInfoArrayList = projectSellDtoService.selectCoopInfoIdAndCoopNameAll();
        return coopInfoArrayList;
    }

    //营销策划保存
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String projectSellDto, String identifying, String code) {
        if (StringUtils.isEmpty(projectSellDto)) {
            return RspVo.getFailureResponse(0, "数据为空");
        }
        String object = StringEscapeUtils.unescapeJava(projectSellDto);
        ProjectSellDto dto = JSON.parseObject(object, ProjectSellDto.class);
        ProSell proSell = projectSellDtoService.selectByProCode(code);
        if ("0".equals(identifying)) {//0是保存
            if ("1".equals(proSell.getProcessStatus()))
            {
                return RspVo.getFailureResponse(0, "审批中保存失败");
            }
            int i = projectSellDtoService.save(dto, code);
            if (i > 0) {
                return RspVo.getSuccessResponse(0, "保存成功");
            } else {
                return RspVo.getFailureResponse(0, "保存失败");
            }
        } else { //1是提交
            //判断标书策划的状态
            if ("1".equals(proSell.getProcessStatus()) || "9".equals(proSell.getProcessStatus())) {
                return RspVo.getFailureResponse(0, "审批中或审批已完成，修改失败");
            }
            //提交流程  先保存
            int i = projectSellDtoService.save(dto, code);
            if (i > 0) {//保存成的情况 走流程
                if (StringUtils.isNotBlank(proSell.getOaId())) {
                    oaFlowService.finishOA(proSell.getOaId());
                }
                //根据唯一procode查询业务表SGUID
                //登录人员信息
                AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
                //发起流程
                String process = proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE3, object, proSell.getId(), code, vo);
                if (!StringUtils.isEmpty(process)) {
                    return RspVo.getSuccessResponse(0, "提交成功");
                }
                return RspVo.getFailureResponse(0, "提交失败");
            } else { //提交-保存失败
                return RspVo.getFailureResponse(0, "提交失败");
            }

        }
    }


    /**
     * 营销策划列表
     *
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-proSell-list";
    }

    /**
     * 营销策划列表数据
     *
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProjectInfo> queryDataByCondition(ProSellVo proSellVo, ParamPage paramPage) throws ParseException {
        Page<ProjectInfo> page = new Page<ProjectInfo>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = proSellService.selectPageByDomainWhere(page, proSellVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 营销策划-我审批的列表数据
     *
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<ProSellDomain> queryMyCheckDataByCondition(ProSellVo proSellVo, ParamPage paramPage) {
        Page<ProSellDomain> page = new Page<ProSellDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (proSellVo.getEndDate() != null) {
            proSellVo.setEndDate(DateUtils.addDays(proSellVo.getEndDate(), 1));
        }
        proSellVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = proSellService.selectMyCheckByDomainWhere(page, proSellVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 营销策划-新增
     *
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可营销策划的立项通过记录
        SetupPro setupPro = new SetupPro();
        setupPro.setProcessStatus("9");
        List<SetupPro> setupPros = setupProService.selectByEntityWhere(setupPro);
        request.setAttribute("setupPros", setupPros);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-proSell-add";
    }

    /**
     * 根据id查询营销策划详情  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param proCode 营销策划proCode
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request, String proCode, String id) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("proCode", proCode);
        ProSell proSell = proSellService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        if (proSell != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proSell.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), proSell.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(proSell.getProcessId()) && proSell.getProcessId().length() > 10) {
                request.setAttribute("processId", proSell.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(proSell.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), proSell.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("id", id);
        return "mkt/lay-marketingPlanning-detail";
    }
//    @RequestMapping("/toDealOrDetail")
//    public ModelAndView queryById(HttpServletRequest request,String id, String processDealWith){
//        Map<String, Object> map = new HashMap<String, Object>();
//        ProSellVo proSell = proSellService.selectById(id);
//        map.put("proSell", proSell);
//        // 审批flag
//        request.setAttribute("processDealWith", processDealWith);
//        // 审批data
//        processData(request, proSell.getProcessId());
//        return new ModelAndView("mkt/lay-proSell-detail", map);
//    }

    @RequestMapping("/toDetail")
    public String queryDetailById(HttpServletRequest request, String id) {
        ProSellVo proSell = proSellService.selectById(id);
        request.setAttribute("proSell", proSell);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        request.setAttribute("edit", "edit");
        return "mkt/lay-proSell-add";
    }

    /**
     * 新增营销策划
     *
     * @return
     */
//    @SuppressWarnings({"rawtypes"})
//    @RequestMapping("/save")
//    public @ResponseBody
//    RspVo save(HttpServletRequest request, ProSellVo proSell) {
//        String fromChannel = request.getParameter("fromChannel");//项目渠道
//        String linkPower = request.getParameter("linkPower");//居住地址
//        if (fromChannel.equals("2")) {//居间合作
//            if (StringUtils.isEmpty(linkPower)) {
//                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间方不能为空");
//            }
//        }
//        String[] sgCoopId = request.getParameterValues("sgCoopId");//单位名称
//        String[] coopEffect = request.getParameterValues("coopEffect");//单位作用
//
//        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
//        String[] subName = request.getParameterValues("subName");//子项名称
//        String[] subWorkYears = request.getParameterValues("subWorkYears");//子项-合作周期（年）
//        String[] subBuildYears = request.getParameterValues("subBuildYears");//子项-建设周期（年）
//        String[] subOmYears = request.getParameterValues("subOmYears");//子项-运营周期（年）
//
//        String[] costOrderIdx = request.getParameterValues("costOrderIdx");//营销费用序号
//        String[] costTypes = request.getParameterValues("costTypes");//费用类型
//        String[] willOccurDate = request.getParameterValues("willOccurDate");//预计日期
//        String[] costMoney = request.getParameterValues("costMoney");//费用金额（元）
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//
//        /**
//         * 营销策划主表处理
//         */
//        String id = IdFactory.getUUIDUpper();
//        proSell.setId(id);
//        proSell.setHrStaffApplyId(vo.getHrStaffId());
//        proSell.setHrOrgId(proSell.getProSellOrgId());
//        proSell.setHrDeptId(proSell.getProSellDeptId());
//        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(vo.getHrStaffId());
//        proSell.setStaffName(staffInfo.getStaffName());
//        proSell.setAddBy(vo.getId());
//        proSell.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String codes = codeGeneratorConfigService.generatorCode("mkt_pro_sell_codes");
//        proSell.setCodes(codes);
//        // 处理processId
//        proSell.setProcessId(IdFactory.getUUIDUpper());
//        proSell.setProcessStatus("1");//审批中
//        proSell.setUptBy(vo.getId());
//        proSell.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //合作单位处理
//        List<ProSellCoop> proSellCoops = new ArrayList<ProSellCoop>();
//        if (sgCoopId != null && sgCoopId.length > 0) {
//            for (int i = 0; i < sgCoopId.length; i++) {
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if (StringUtils.isEmpty(coopId) && StringUtils.isEmpty(coopeffect)) {
//                    continue;
//                }
//                String coopid = IdFactory.getUUIDUpper();//自动生成主键
//                ProSellCoop proSellCoop = new ProSellCoop();
//                proSellCoop.setId(coopid);
//                proSellCoop.setProSellId(id);
//                proSellCoop.setSgCoopId(coopId);
//                proSellCoop.setCoopEffect(coopeffect);
//                proSellCoop.setAddBy(vo.getId());
//                proSellCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                proSellCoops.add(proSellCoop);
//            }
//
//        }
//
//        //子项处理
//        List<ProSellSub> proSellSubs = new ArrayList<ProSellSub>();
//        for (int i = 0; i < orderIdx.length; i++) {
//            String orderId = orderIdx[i];
//            ProSellSub proSellSub = new ProSellSub();
//            String subId = IdFactory.getUUIDUpper();//自动生成主键
//            proSellSub.setId(subId);
//            proSellSub.setProSellId(id);
//            proSellSub.setOrderIdx(Integer.parseInt(orderId));
//            proSellSub.setSubName(subName[i]);
//            proSellSub.setWorkYears(new BigDecimal(subWorkYears[i]));
//            proSellSub.setBuildYears(new BigDecimal(subBuildYears[i]));
//            proSellSub.setOmYears(new BigDecimal(subOmYears[i]));
//            proSellSub.setAddBy(vo.getId());
//            proSellSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//            proSellSubs.add(proSellSub);
//        }
//        /**
//         * 营销费用集合
//         */
//        List<ProSellCost> proSellCosts = new ArrayList<ProSellCost>();
//        for (int i = 0; i < willOccurDate.length; i++) {
//            if (StringUtils.isNotEmpty(costMoney[i]) && StringUtils.isNotEmpty(willOccurDate[i])) {
//                String orderId = costOrderIdx[i];
//                ProSellCost proSellCost = new ProSellCost();
//                String subId = IdFactory.getUUIDUpper();//自动生成主键
//                proSellCost.setId(subId);
//                proSellCost.setProSellId(id);
//                proSellCost.setOrderIdx(Integer.parseInt(orderId));
//                proSellCost.setTypes(costTypes[i]);
//                proSellCost.setCostMoney(new BigDecimal(costMoney[i]));
//                proSellCost.setWillOccurDate(DateUtil.parseYYYYMMDDDate(willOccurDate[i]));
//                proSellCost.setAddBy(vo.getId());
//                proSellCost.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                proSellCosts.add(proSellCost);
//            }
//        }
//        proSellService.addProSell(proSell, proSellCoops, proSellSubs, proSellCosts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "营销策划 -新增营销策划：项目名=" + proSell.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }


    @RequestMapping("/edit")
    public @ResponseBody
    RspVo edit(HttpServletRequest request, ProSellVo proSell) {
        String submitType = request.getParameter("submitType");//2=提交  1保存
        String fromChannel = request.getParameter("fromChannel");//项目渠道
        String linkPower = request.getParameter("linkPower");//居住地址
        if ("2".equals(fromChannel)) {//居间合作
            if (StringUtils.isEmpty(linkPower)) {
                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间方不能为空");
            }
        }


        String[] costOrderIdx = request.getParameterValues("costOrderIdx");//营销费用序号
        String[] costTypes = request.getParameterValues("costTypes");//费用类型
        String[] willOccurDate = request.getParameterValues("willOccurDate");//预计日期
        String[] costMoney = request.getParameterValues("costMoney");//费用金额（元）
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
         * 营销策划主表处理
         */
        String id = proSell.getId();
        proSell.setUptBy(vo.getId());
        proSell.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        /**
         * 营销费用集合
         */
        List<ProSellCost> proSellCosts = new ArrayList<ProSellCost>();
        for (int i = 0; i < willOccurDate.length; i++) {
            if (StringUtils.isNotEmpty(costMoney[i]) && StringUtils.isNotEmpty(willOccurDate[i])) {
                String orderId = costOrderIdx[i];
                ProSellCost proSellCost = new ProSellCost();
                String subId = IdFactory.getUUIDUpper();//自动生成主键
                proSellCost.setId(subId);
                proSellCost.setProSellId(id);
                proSellCost.setOrderIdx(Integer.parseInt(orderId));
                proSellCost.setTypes(costTypes[i]);
                proSellCost.setCostMoney(new BigDecimal(costMoney[i]));
                proSellCost.setWillOccurDate(DateUtil.parseYYYYMMDDDate(willOccurDate[i]));
                proSellCost.setAddBy(vo.getId());
                proSellCost.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                proSellCosts.add(proSellCost);
            }
        }
        proSellService.editProSell(proSell, proSellCosts, submitType);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "营销策划 -新增营销策划：项目名=" + proSell.getProName(), null);
        return RspVo.getSuccessResponse();
    }


    /**
     * 根据id查询营销策划记录
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/getProSellById")
    @ResponseBody
    public Map<String, Object> getProSellById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            ProSellVo proSellVo = proSellService.selectById(id);
            AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//            proSellVo.setStaffName(staffInfo.getStaffName());
            map.put("proSellVo", proSellVo);
        } catch (Exception e) {
            log.error("查询营销策划记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }
}
